package web

import (
	"bigdevops/src/common"
	"bigdevops/src/config"
	"bigdevops/src/web/middleware"
	"bigdevops/src/web/view_alertwebhook"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/requestid"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/alertmanager/template"
	ginprometheus "github.com/zsais/go-gin-prometheus"
	"net/http"
	"time"
)

func AlertWebhookStartGin(sc *config.AlertWebhookConfig, alertReceiveQ chan template.Alert) error {

	// 初始化引擎
	//gin.SetMode(gin.ReleaseMode)
	//r := gin.Default()
	r := gin.New()
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "OPTIONS"},
		AllowHeaders:     []string{"Origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		//AllowOriginFunc: func(origin string) bool {
		//	return origin == "https://github.com"
		//},
		MaxAge: 12 * time.Hour,
	}))
	r.Use(gin.Recovery())
	// 定义需要传递 变量的map
	// 把logger传进去
	varMap := map[string]interface{}{}
	//varMap[common.GIN_CTX_CONFIG_LOGGER] = sc.Logger
	varMap[common.GIN_CTX_CONFIG_CONFIG] = sc
	varMap[common.GIN_CTX_CONFIG_ALERTRECEIVEQ] = alertReceiveQ

	// 传递变量的
	r.Use(middleware.ConfigMiddleware(varMap))
	// 这是打印耗时的
	//r.Use(middleware.TimeCost())
	// 请求id
	r.Use(requestid.New())
	// 3个作用 记录 请求id、请求body、header中的token 到zap日志中
	r.Use(middleware.NewGinZapLogger(sc.Logger))

	// 暴露metrics
	p := ginprometheus.NewPrometheus("bigdevops")
	p.Use(r)
	//r.Use(ginzap.Ginzap(sc.Logger, time.RFC3339, false))

	//r.Use(gin.Timeout(time.Second * 10))
	gin.DisableConsoleColor()

	// 配置路由
	view_alertwebhook.ConfigRoutes(r)
	// http 读写超时参数
	s := &http.Server{
		Addr:           sc.HttpAddr,
		Handler:        r,
		ReadTimeout:    time.Second * 20,
		WriteTimeout:   time.Second * 20,
		MaxHeaderBytes: 1 << 20,
	}

	return s.ListenAndServe() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")

}

func AlertWebhookConfigRoutes(r *gin.Engine) {
	base := r.Group("/")
	{
		base.GET("/ping", ping)

	}

}
